<?php
namespace app\index\controller;
use app\admin\model\Product;
use app\admin\model\User;
use app\index\model\IntegralUsed;
use Gatewayclient\Gateway;
use think\Controller;
use Wxpay\Wechat;
use Wxpay\WechatException;
use Alidayu\Alidayu;
use app\admin\model\Indent;
use app\index\model\PayOrder;
use think\Db;

class Pay {

    //微信支付
    public function wechat(){
        header('Content-type:text/html;charset=utf-8');
        if(empty($_GET['code']) || empty($_GET['state']))die('购买失败:empty param');
        $indent = new Indent();
		list($indentid,$poid) = explode('|',$_GET['state']);
        $order = $indent::get($indentid);
        $order['title'] = (new Product())->where('id',$order['i_pid'])->value('p_name');
        if(empty($order))die('该订单不存在');
        $pay_order = new PayOrder();
        $payorder = $pay_order -> where("id",$poid) -> find();
        $wConf = v('wechat');
        try {
            Wechat::setAppId($wConf['appid']);
            Wechat::setAppSecret($wConf['appsecret']);
            Wechat::setMchId($wConf['mch_id']);
            Wechat::setKey($wConf['key']);
            $oauth = Wechat::oauth($_GET['code']);
            $openId = $oauth['openid'];
            Wechat::setParam('openid', $openId);
            Wechat::setParam('body', $order['title']);
            Wechat::setParam('out_trade_no', $payorder['order']);
            Wechat::setParam('total_fee', $order['i_totprice'] * 100);
            Wechat::setParam('notify_url', url('Pay/wechatNotify@'.$_SERVER['HTTP_HOST']));
            Wechat::setParam('trade_type', 'JSAPI');
            Wechat::setParam('time_expire', date('YmdHis', strtotime('+2 hours')));
            //统一订单接口
            $res = Wechat::unifiedorder();
            $prepayId = $res['prepay_id'];

            $this->wechatContinuePay($prepayId);
        }catch(WechatException $e){
            if($e->getCode()=='40029'){
                $this ->redirect('index/index');
            }
            die($e->getMessage());
        }
    }

    //微信继续支付
    public function wechatContinuePay($prepayId,$callbackUrl=null)
    {
        if(is_null($callbackUrl))$callbackUrl = url('indent/done@'.$_SERVER['HTTP_HOST']);
        Wechat::setAppId(v('wechat.appid'));
        Wechat::goPay($prepayId,$callbackUrl,url('Pay/wechatContinuePay@'.$_SERVER['HTTP_HOST']).'?prepayId='.$prepayId);
    }

    /**
     * 微信支付通知接口
     */
    public function wechatNotify()
    {
        $data = $GLOBALS['HTTP_RAW_POST_DATA'];
        $data = Wechat::xmlToArray($data);

        $sign = $data['sign'];
        unset($data['sign']);
        $orderNo = $data['out_trade_no'];
        $transaction_id = $data['transaction_id'];
        Wechat::setKey(v('wechat.key'));
        if ($sign != Wechat::getSign($data)) {
            $res = array(
                'return_code' => 'FAIL',
                'return_msg' => '签名失败'
            );
            echo Wechat::arrayToXml($res);die;
        } else {
            if ($data['return_code'] == 'FAIL') {

            } elseif ($data['result_code'] == 'FAIL') {

            } else {
                //成功支付后回调修改订单状态
                Db::name('pay_order') -> where('order',$orderNo) -> update(['status'=>1,'trade_no'=>$transaction_id,'pay_time'=>time()]);
                $indentid = Db::name('pay_order') -> where('order',$orderNo) -> value('indentid');
                Db::name('indent')->where('id',$indentid)->update(['i_status'=>1,'pay_time'=>time()]);

//                self::success($indentid);

                $find = Db::name('indent') -> where('id',$indentid) -> find();
                //如使用了积分则修改使用积分状态
                if($find['i_uintegral'] > 0){
                    (new IntegralUsed())->save(['iu_status'=>1],['iu_indentid'=>$find['id']]);
                }

                //推广人获得积分
                if($find['i_type']==1){
                    if($find['dealer_id']!=0){
                        $ii = [
                            'indent_id' =>  $find['id'],
                            'user_id'   =>  $find['dealer_id'],
                            'integral'  =>  1,
                            'type'      =>  1
                        ];
                        Db::name('indent_integral')->insert($ii);
                    }
                }else if($find['i_type']==2){
                    if($find['dealer_id']>0){
                        $ii = [
                            'indent_id' =>  $find['id'],
                            'user_id'   =>  $find['dealer_id'],
                            'integral'  =>  60,
                            'type'      =>  2
                        ];
                        Db::name('indent_integral')->insert($ii);
                    }
                    if($find['p_id']>0){
                        $ii = [
                            'indent_id' =>  $find['id'],
                            'user_id'   =>  $find['p_id'],
                            'integral'  =>  60*0.3,
                            'type'      =>  2
                        ];
                        Db::name('indent_integral')->insert($ii);
                    }
                }

                //把手机号作为登录账号进行后期登录推广
                $user = new User();
                $et_id = $user -> where('u_username',$find['i_phone'])->value('id');
                $rand='';
                if($et_id>0) {
                    Db::name('indent')->where('id',$find['id'])->setField('i_uid', $et_id);
                    $user -> save(["p_id"=>$find['p_id'],"dealer_id"=>$find['dealer_id']],["id"=>$et_id]);
                }else{
                    $rand = rand(100000,999999);
                    $user_data = [
                        'u_nickname'    => $find['i_uname'],
                        'u_username'    => $find['i_phone'],
                        'u_password'    => md5($rand),
                        'create_time'   => time(),
                        'p_id'          => $find['p_id'],
                        'dealer_id'     => $find['dealer_id'],
                        'u_type'        => 1
                    ];
                    $add_et = $user->insertGetId($user_data);
                    Db::name('indent')->where('id',$find['id'])->setField('i_uid', $add_et);
                }

                //处理后同步返回给微信
                $res = array(
                    'return_code' => 'SUCCESS',
                    'return_msg' => 'OK'
                );
                return xml($res);

                //发送短信通知开通账号
                $alidayu = new Alidayu();
                $content = '{"phone":"' . $find['i_phone'] . '","pwd":"' . $rand . '"}';
                $result = $alidayu->sendSms($find['phone'], 'SMS_56610214', $content);
                //发送成功后记录到文件中
                if ($result == 0) {
                    $status = '发送成功【微信支付成功后开通账号通知】';
                    rwLog($find['i_phone'], $status);
                } else {
                    $status = '发送失败【微信支付成功后开通账号通知】';
                    rwLog($find['i_phone'], $status);
                }

                //推送"提示购买成功"消息到后台
                //uid：用户id nickname：用户昵称 order：订单号 status：订单状态 time：订单完成时间
                $nickname = User::get($find['uid']);
                $indent_message = ['uid'=>$find['i_uid'],'nickname'=>$nickname['u_nickname '],'order'=>$find['i_number'],'i_totprice'=>$find['i_totprice'],'status'=>1,'time'=>time()];
                Gateway::sendToGroup(2,json_encode($indent_message));
            }
        }
    }


//    /**
//     * @title   indent和pay_order表修改状态都成个后的操作
//     * @param mixed|string $indentid    订单id
//     * @return xml
//     */
//    protected static function success($indentid){
//        $find = Db::name('indent') -> field('id,i_phone,i_type,i_uname,p_id,dealer_id,i_uintegral') -> where('id',$indentid) -> find();
//        //如使用了积分则修改使用积分状态
//        if($find['i_uintegral'] > 0){
//            (new IntegralUsed())->save(['iu_status'=>1],['iu_indentid'=>$find['id']]);
//        }
//
//        //推广人获得积分
//        self::addintegral($find);
//
//        //把手机号作为登录账号进行后期登录推广
//        $pwd = self::addexten($find);
//
//        //处理后同步返回给微信
//        $res = array(
//            'return_code' => 'SUCCESS',
//            'return_msg' => 'OK'
//        );
//        return xml($res);
//
//        //发送短信通知开通账号(未申请)
//        if(!empty($pwd)) {
//            $alidayu = new Alidayu();
//            $content = '{"phone":"' . $find['i_phone'] . '","pwd":"' . $pwd . '"}';
//            $result = $alidayu->sendSms($find['phone'], 'SMS_56610214', $content);
//            //发送成功后记录到文件中
//            if ($result == 0) {
//                $status = '发送账户成功【微信支付成功后开通账号通知】';
//                rwLog($find['i_phone'], $status);
//            } else {
//                $status = '发送账户失败【微信支付成功后开通账号通知】';
//                rwLog($find['i_phone'], $status);
//            }
//        }
//    }

//    /**
//     * @title   创建用户账号
//     * @param $find     支付订单的详细内容
//     * @return int|string   返回创建账号的密码
//     */
//    protected static function addexten(array $find){
//        $user = new User();
//        $et_id = $user -> where('u_username',$find['i_phone'])->value('id');
//        $rand='';
//        if($et_id>0) {
////            Db::name('indent')->where('id',$find['id'])->setField('i_uid', $et_id);
////            $user -> save(["p_id"=>$find['p_id'],"dealer_id"=>$find['dealer_id']],["id"=>$et_id]);
//        }else{
//            $rand = rand(100000,999999);
//            $user_data = [
//                'u_nickname'    => $find['i_uname'],
//                'u_username'    => $find['i_phone'],
//                'u_password'    => md5($rand),
//                'u_type'        => 1,
//                'create_time'   => time(),
//                'p_id'          => $find['p_id'],
//                'dealer_id'     => $find['dealer_id']
//            ];
//            $add_et = $user->insertGetId($user_data);
//            Db::name('indent')->where('id',$find['id'])->setField('i_uid', $add_et);
//        }
//        return isset($rand)?$rand:'';
//    }
//
//    /**
//     * @title   推广人获得积分
//     * @param $find     支付订单的详细内容
//     * @param $find['i_type']   1:免费领取 2:套装
//     */
//    protected static function addintegral(array $find)
//    {
//        if($find['i_type']==1){
//            if($find['dealer_id']>0){
//                $ii = [
//                    'indent_id' =>  $find['id'],
//                    'user_id'   =>  $find['dealer_id'],
//                    'integral'  =>  1,
//                    'type'      =>  1
//                ];
//                Db::name('indent_integral')->insert($ii);
//            }
//        }else{
//            if($find['dealer_id']>0){
//                $ii = [
//                    'indent_id' =>  $find['id'],
//                    'user_id'   =>  $find['dealer_id'],
//                    'integral'  =>  60,
//                    'type'      =>  2
//                ];
//                Db::name('indent_integral')->insert($ii);
//            }
//            if($find['p_id']>0){
//                $ii = [
//                    'indent_id' =>  $find['id'],
//                    'user_id'   =>  $find['p_id'],
//                    'integral'  =>  60*0.3,
//                    'type'      =>  2
//                ];
//                Db::name('indent_integral')->insert($ii);
//            }
//        }
//    }
}